import {defer} from "@/utils/defer";

export async function getConfiguration(){
  // scan.scss.json 是运行 plain-ui 的 ——-> ts-node src/styles/data/scan.scss.ts 脚本 打包出来的
  // const target = 'plain-ui/src/style/data/scan.scss.json'; // ← 提出来 默认是打包不到的 就会报错

  //todo 这个路径后面要改成我们自己ui库的
  const themeData = (await import('plain-ui/src/style/data/scan.scss.json')).default as {
    globalImport: string;
    packagesScss: { name: string, seq: number, codes: string[] }[];
  }
  console.log('themeData:',themeData);
  console.log('themeData.globalImport:',themeData.globalImport);
  const {defaultEditData, defaultVariables} = decodeGlobalImport(themeData.globalImport);
  const {generateVariables, generateCssFile} = getThemeCompiler(themeData.globalImport, themeData.packagesScss);

  console.log('defaultEditData:',defaultEditData);
  console.log('defaultVariables:',defaultVariables);
  return {
    defaultEditData,
    defaultVariables,
    generateVariables,
    generateCssFile
  }
}

function decodeGlobalImport(globalImport:string){
  // $theme-default: (
  //   '':(
  //     colorPrimary: #12b4a5,                                  /*基础*/
  //     colorSuccess: #00CC00,                                  /*成功*/
  //     colorWarn: #FF7400,                                     /*警告*/
  //     colorError: #F38585,                                    /*错误*/
  //     colorInfo:#969696,                                      /*帮助*/
  //     ...
  //   )
  // )
  const match = globalImport.match(/\$theme-default:(?:(?:\s)*)\((?:(?:\s)*)'':\((?:(?:\s)*)(\S(?:.|\r|\n)*)(?:(?:\s)*)\)(?:(?:\s)*)\);/)
  console.log('match:',match); //非全局匹配match 返回结果的第一项是匹配到
  if (!match) {
    throw new Error('解析 globalImport 失败，无法匹配到 theme-default！')
  }
  const lines = match[1].split(/(\r\n)+/);

  /*默认的主题样式表单编辑对象*/
  const defaultEditData: Record<string, string> = {}
  /*默认的变量信息数组*/
  const defaultVariables: { key: string, value: string, comments: string }[] = []

  lines.filter(line => !!line.trim()).forEach(line => {
    //colorPrimary: #12b4a5,                                  /*基础*/
    let [key, value, comments] = line.split(/(?::|,(?!.*,))/)
    key = key.trim(); // colorPrimary
    value = value.trim(); // #12b4a5
    if (/\d*px/.test(value)) {
      value = removeUnit(value);
    }
    comments = comments.trim(); // /*基础*/
    if (excludeVariables.indexOf(key) === -1) {
      defaultEditData[key] = value;
    }
    defaultVariables.push({key, value, comments});
  })

  return {
    // 基本就是 theme/default.scss 里的数据
    defaultEditData,            // 主题变量集合,key为变量名称,value为变量值 (过excludeVariables移除了部分变量, 且不包含注释)
    defaultVariables,           // 主题变量数组,是完整的数据 (包含注释)
  }
}

/**
 * 主题中不可编辑的变量
 */
const excludeVariables = [
  'font',
  'transitionFlexible',
  'transition',
  'transition2',
  'boxshadow',
  'boxshadowColor',
  'popperRadius',
]

export const removeUnit = (data: string | number | undefined | null, unit = 'px'): string => {
  if (!data) return ''
  data = String(data)
  if (data.indexOf(unit) > -1) {
    return data.replace(unit, '')
  } else {
    return data
  }
}

function getThemeCompiler(globalImport: string, packagesScss: { name: string, seq: number, codes: string[] }[]) {
  //todo theme-blue ---> theme-custome

  /*"$theme-blue: (
    'blue':(
      colorPrimary: #409EFF,
      colorSuccess: #67C23A,
      colorWarn: #E6A23C,
      colorError: #F56C6C,
      colorInfo:#909399,

      shapeFillet:4px,
    ),
    'violet':(
      colorPrimary: #8A2BE2,
      colorSuccess: #4caf50,
      colorWarn: #ff9800,
      colorError: #e91e63,
      colorInfo:#000042,

      shapeFillet:8px,
    )
  );"*/
  const themeCustomMatch = (globalImport).match(/\$theme-blue:[.\s]*\(((?:.|\r|\n)*?)\);/)
  if(!themeCustomMatch){
    throw new Error('解析 globalImport 失败，无法匹配到 theme-custom！')
  }
  console.log('themeCustomMatch:',themeCustomMatch);
  const [m, g1] = themeCustomMatch
  //g1 --> group1:
  /*'blue':(
    colorPrimary: #409EFF,
    colorSuccess: #67C23A,
    colorWarn: #E6A23C,
    colorError: #F56C6C,
    colorInfo:#909399,

    shapeFillet:4px,
  ),
  'violet':(
    colorPrimary: #8A2BE2,
    colorSuccess: #4caf50,
    colorWarn: #ff9800,
    colorError: #e91e63,
    colorInfo:#000042,

    shapeFillet:8px,
  )*/

  // 编译获取scss主题变量文件
  /*
    就是生成新的
    $custom-theme: (
      'xxx':(
        colorPrimary: #ff...
      )
      'yyy':( ....
    )
  */
  const generateVariables = (themeData: Record<string, string>, themeName: string) => {
    const themeString = Object.entries(themeData).map(([key, value]) => {
      let val = value as string | number;
      if(/^\d*$/.test(String(val))) {
        val = `${val}px`;
      }
      return `${key}:${val},`;
    }).join('\n\t');

    return m.replace(g1,`'${themeName}':(
  ${themeString}
)`)
  };

  // 编译获取css主题色文件
  const generateCssFile = (themeData: Record<string, string>, themeName: string) => {
    console.log('generateCssFile --- --- ---');
    console.log('themeData:',themeData);
    console.log('themeName:',themeName);
    const theme = generateVariables(themeData, themeName);
    let newGlobalImport = globalImport.replace(m, theme);
    if (themeName.trim() !== '') {
      newGlobalImport = newGlobalImport.replace('$generate_default: true;', '$generate_default: false;');
    }
    //newGlobalImport主要是 @mixin theme 这个mixin
    //packagesScss里才是各个组件的scss
    const scss = `${newGlobalImport} ${packagesScss.map(({codes}) => codes.join('')).join('')}`;
    return compile(scss);
  };

  return {
    generateCssFile,
    generateVariables
  }
}


const compile = async (code: string) => {
  console.log('compile --- --- ---');
  console.log('code:',code);
  // sass(dart-sass) 不支持client,即不支持在浏览器上直接用, 只能在node端用
  /*return sass.renderSync({
    data: code
  }).css.toString();*/

  // console.log('Sass:',Sass)
  const dfd = defer<string>();
  //@ts-ignore
  (window as any).Sass.compile(code, result => {
    console.log('最终生成的css:', result);
    console.log('最终生成的css:', result.text);
    dfd.resolve(result.text);
  });
  return dfd.promise
}
